package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.content.RedisConstants.*;

@Component
@Service
public class CacheClient {


    private final StringRedisTemplate stringRedisTemplate;


    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key , Object value,Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    /**
     * 逻辑过期
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setWithLogicalExpire(String key , Object value,Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透（写入空串）
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithPass(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback ,
        Long time , TimeUnit unit) {
        //1、从redis查询数据
        String key = keyPrefix + id;
        String lockKey = keyPrefix + id;

        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3、如果存在返回数据
            return JSONUtil.toBean(json,type);
        }
        //查看是否为空
        if (json != null) {
            //该redis数据为空
            return null;
        }

        //4.3成功根据id查询数据库

        R r = dbFallback.apply(id);
            if (r == null) {
                //5、不存在，返回错误
                //防止缓存穿透，写入空串
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6、存在写入redis
        this.set(key,r,time,unit);
        //8、返回
        return r;
    }

    //创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期
     * @param id
     * @return
     */
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> type,Function<ID,R> dbFallback,
                                           Long time , TimeUnit unit) {
        //1、从redis查询数据
        String key = keyPrefix + id;

        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否命中
        if (StrUtil.isBlank(json)) {
            //3、如果没命中，返回空.
            return null;
        }
        //4.命中，将数据解析成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(),type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断数据是否过期
        if ( expireTime.isAfter(LocalDateTime.now())){
            //5.1未过期，直接返回数据
            return r;
        }
        //6.已过期，需要缓存重建，获取锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean islock = tryLock(lockKey);
        //7.判断是否获取锁
        if (islock){
            //1再次判断
            json = stringRedisTemplate.opsForValue().get(key);
            //2、判断是否命中
            if (StrUtil.isBlank(json)) {
                //3、如果没命中，返回空.
                return null;
            }
            //4命中，将数据解析成对象
            redisData = JSONUtil.toBean(json, RedisData.class);
            r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
            //5.判断数据是否过期
            expireTime = redisData.getExpireTime();
            //5.判断数据是否过期
            if ( expireTime.isAfter(LocalDateTime.now())){
                //未过期，直接返回数据
                return r;
            }
            //数据依旧过期，继续重建
            //7.1获取锁开启独立线程，
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    //查询数据库
                    R apply = dbFallback.apply(id);
                    //写入redis
                    setWithLogicalExpire(key,apply,time,unit);
                }catch (Exception e){
                    //释放锁
                    unLock(lockKey);
                }
            });
            //关闭线程池
            CACHE_REBUILD_EXECUTOR.shutdown();
        }
        //8.未获取，直接返回数据
        return r;
    }



    /**
     * redis缓存问题解决方案（互斥锁）
     * @param id
     * @return
     */
    public<R,ID> R queryWithMutex(String keyPrefix,ID id, Class<R> type,Function<ID,R> dbFallback,
                               Long time , TimeUnit unit) {
        //1、从redis查询数据
        String key = keyPrefix + id;
        String lockKey = LOCK_SHOP_KEY + id;

        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3、如果存在返回数据
            return JSONUtil.toBean(json, type);
        }
        //查看是否为空
        if (json != null) {
            //该redis数据为空
            return null;
        }

        //4、不存在，根据id查询数据库
        //4.1获取互斥锁
        R r = null;
        try {
            boolean tryLock = tryLock(lockKey);
            //4.2判断获取是否成功
            while (!tryLock) {
                //4.2.1如果失败，则休眠并且重试
                Thread.sleep(50);
            }
//        if (!tryLock){
//            Thread.sleep(50);
//        }

            //再次判定
            json = stringRedisTemplate.opsForValue().get(key);
            //2、判断是否存在
            if (StrUtil.isNotBlank(json)) {
                //3、如果存在返回数据
                unLock(lockKey);
                return JSONUtil.toBean(json, type);
            }
            //查看是否为空
            if (json != null) {
                //该redis数据为空
                unLock(lockKey);
                return null;
            }


            //4.3成功根据id查询数据库

            r = dbFallback.apply(id);
            if (r == null) {
                //5、不存在，返回错误
                //防止缓存穿透，写入空串
                stringRedisTemplate.opsForValue().set(key, "", time,unit);
                unLock(lockKey);
                return null;
            }
            //6、存在写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), time, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        //7.释放互斥锁
        //8、返回
        return r;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){

        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    /**
     * 释放锁
     * @param key
     */
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
